package com.dimples.dd.security.core.interceptor;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.util.StrUtil;
import com.dimples.dd.common.constant.DDConstant;
import com.dimples.dd.common.result.CommonResult;
import com.dimples.dd.common.result.ResultCode;
import com.dimples.dd.common.util.DDUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2024/6/7
 */
public class DDServerProtectInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = request.getHeader(DDConstant.GATEWAY_TOKEN_HEADER);
        String gatewayToken = Base64Encoder.encode(DDConstant.GATEWAY_TOKEN_VALUE.getBytes());
        if (StrUtil.equals(gatewayToken, token)) {
            return true;
        } else {
            CommonResult<String> result = CommonResult.error(ResultCode.GATEWAY_TOKEN_ERROR);
            DDUtil.makeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, result);
            return false;
        }
    }
}
